package com.example.multiactivity

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import java.util.Locale

class FourthActivity : AppCompatActivity() {
    private lateinit var viewModel: StopwatchViewModel
    private lateinit var tvTime: TextView
    private lateinit var btnStart: Button
    private lateinit var btnPause: Button
    private lateinit var btnReset: Button
    private val handler = Handler(Looper.getMainLooper())
    private val runnable = object : Runnable {
        override fun run() {
            viewModel.elapsedTime = System.currentTimeMillis() - viewModel.startTime
            updateTimeDisplay()
            handler.postDelayed(this, 10)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fourth)

        viewModel = ViewModelProvider(this)[StopwatchViewModel::class.java]

        tvTime = findViewById(R.id.tv_time)
        btnStart = findViewById(R.id.btn_start)
        btnPause = findViewById(R.id.btn_pause)
        btnReset = findViewById(R.id.btn_reset)

        updateTimeDisplay()
        if (viewModel.isRunning) {
            startTimer()
        }

        btnStart.setOnClickListener {
            if (!viewModel.isRunning) {
                viewModel.startTime = System.currentTimeMillis() - viewModel.elapsedTime
                viewModel.isRunning = true
                startTimer()
            }
        }

        btnPause.setOnClickListener {
            if (viewModel.isRunning) {
                viewModel.isRunning = false
                handler.removeCallbacks(runnable)
            }
        }

        btnReset.setOnClickListener {
            viewModel.isRunning = false
            viewModel.elapsedTime = 0L
            handler.removeCallbacks(runnable)
            updateTimeDisplay()
        }
    }

    private fun startTimer() {
        handler.post(runnable)
    }

    private fun updateTimeDisplay() {
        val minutes = (viewModel.elapsedTime / 1000 / 60).toInt()
        val seconds = (viewModel.elapsedTime / 1000 % 60).toInt()
        val millis = (viewModel.elapsedTime % 1000 / 10).toInt()
        tvTime.text = String.format(Locale.getDefault(), "%02d:%02d.%02d", minutes, seconds, millis)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(runnable)
    }
}